import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from "vue-router";
import Layout from '@/components/Layout/index.vue'

let routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: () => import('@/views/login/index.vue')
  },
  {
    path: '/previewImage',
    component: () => import('@/views/common/previewImage.vue')
  },
  {
    path: '/home',
    name: 'home',
    component: Layout,
    children: [
      {
        path: '',
        component: () => import('@/views/home/index.vue')
      },
      {
        path: 'index',

        component: () => import('@/views/home/index2.vue')
      },
      {
        path: 'index2',
        component: () => import('@/views/home/index3.vue')
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*', // 匹配所有未定义的路由
    component: () => import("@/components/ErrorMessage/404.vue")
  }
]

//批量处理modules里面的路由
let importRouter: Array<RouteRecordRaw> = []
const files: Record<string, any> = import.meta.glob('./modules/*.ts', { eager: true })

for (const key in files) {
  const fileRouters: RouteRecordRaw[] = files[key].default
  importRouter = importRouter.concat(fileRouters)
}
//将modules中的路由拼接进主路由
function getRoutes(): Array<RouteRecordRaw> {
  return routes.concat(importRouter)
}

const router = createRouter({
  history: createWebHistory(),
  routes: getRoutes()
})
router.beforeEach((to: any, from, next) => {
  const token = sessionStorage.getItem('token')
  if (to.path == '/' || to.path == '/login' || to.path == '/previewImage') {
    next()
  }

  if (to.matched[0].path != "/:pathMatch(.*)*") {
    if (!token) {
      // 如果没有token，重定向到登录页面
      next({ path: '/login' });
    } else {
      // 如果有token，继续访问
      next();
    }
  } else {
    next()
  }
})
export default router
